package com.fdb.efp.flow.api.rest;

/**
 *  *
 * @author luzhaoyu
 * @version 0.1
 * @date 2019/9/12
 * @since 2019/9/12
 *
 */


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fdb.basic.framework.core.constant.*;
import com.fdb.basic.framework.core.util.TimeUtil;
import com.fdb.basic.framework.core.vo.EngineHttpRequestVO;
import com.fdb.basic.framework.web.util.HttpClientUtil;
import com.fdb.basic.sequence.service.facade.SequenceService;
import com.fdb.efp.console.common.ConsoleConstant;
import com.fdb.efp.console.service.facade.PubSysInfoService;
import com.fdb.efp.e4a.service.facade.SRoleDataRuleService;
import com.fdb.efp.flow.common.constance.FlowConstance;
import com.fdb.efp.flow.executor.util.AbstractController;
import com.fdb.efp.flow.service.FlowCommonService;
import com.fdb.efp.flow.service.FlowRepulseUtil;
import com.fdb.efp.flow.service.facade.BizFlowInfoService;
import com.fdb.efp.flow.service.facade.FlowUrlConfigService;
import com.fdb.efp.flow.service.vo.BizFlowInfoVO;
import com.fdb.efp.loan.service.facade.AccLoanService;
import com.fdb.efp.loan.service.vo.AccLoanVO;
import com.fdb.efp.riskm.service.facade.LmtFreezeAppService;
import com.fdb.efp.riskm.service.facade.LmtTerminateAppService;
import com.fdb.efp.riskm.service.vo.LmtFreezeAppVO;
import com.fdb.efp.riskm.service.vo.LmtTerminateAppVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;


@RestController
@RequestMapping("/api")
public class LmtFreezeAppController extends AbstractController {

    @Autowired
    @Qualifier("lmtFreezeAppService")
    private LmtFreezeAppService lmtFreezeAppService;

    @Autowired
    @Qualifier("lmtTerminateAppService")
    private LmtTerminateAppService lmtTerminateAppService;

    @Autowired
    @Qualifier("accLoanService")
    private AccLoanService accLoanService;

    @Autowired
    @Qualifier("bizFlowInfoService")
    private BizFlowInfoService bizFlowInfoService;

    @Autowired
    @Qualifier("flowUrlConfigService")
    private FlowUrlConfigService flowUrlConfigService;

    @Autowired
    private SequenceService sequenceService;

    @Autowired
    @Qualifier("pubSysInfoService")
    private PubSysInfoService pubSysInfoService;

    @Autowired
    private FlowCommonService flowCommonService;

    @Autowired
    @Qualifier("flowRepulseUtil")
    private FlowRepulseUtil flowRepulseUtil;

    @Autowired
    @Qualifier("sRoleDataRuleService")
    private SRoleDataRuleService sRoleDataRuleService;

    /**
     * 列表数据查询
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "/lmt/freeze/apps", method = RequestMethod.POST)
    public @ResponseBody
    ResponseData<List<LmtFreezeAppVO>> queryLmtFreezeAppAll(@RequestBody LmtFreezeAppVO vo) {
        List<LmtFreezeAppVO> outputVo = null;
        Map<String, String> dataRuleTypeMap = sRoleDataRuleService.getDataRuleType(httpRequest.getRequestURI(), getUserRoles());
        vo.setPrdCodebyBaseInfo(dataRuleTypeMap == null ? null : dataRuleTypeMap.get(PubConstant.PRD_CODE));
        DataRuleType dataRuleType = DataRuleType.getDataRuleType(dataRuleTypeMap == null ? null : dataRuleTypeMap.get(PubConstant.PERMIS_TYPE));
        setUserInfoToVO(vo);
        // 根据权限方案调用不同的方案进行数据查询
        switch (dataRuleType) {
            case Owner:
                outputVo = lmtFreezeAppService.queryAllOwner(vo);
                break;
            case CurrOrg:
                outputVo = lmtFreezeAppService.queryAllCurrOrg(vo);
                break;
            case CurrDownOrg:
                outputVo = lmtFreezeAppService.queryAllCurrDownOrg(vo);
                break;
            case CurrOwnerPrd:
                outputVo = lmtFreezeAppService.queryAllCurrOwnerPrd(vo);
                break;
            default:
                outputVo = lmtFreezeAppService.queryAllCurrOwnerPrd(vo);
                break;
        }
        flowCommonService.displayOrgName(outputVo, "orgCode", "orgName");
        flowCommonService.displayUserName(outputVo, "cusManager", "cusManagerName");
        flowCommonService.displayUserName(outputVo, "lastUpdateUser", "lastUpdateUserName");
        flowCommonService.displayUserName(outputVo, "createUser", "createUserName");
        return getResponseData(outputVo);

    }

    /**
     * 根据主键删除信息
     *
     * @param inLmtFreezeAppVo
     * @return
     */
    @RequestMapping(value = "/lmt/freeze/app", method = RequestMethod.DELETE)
    public @ResponseBody
    ResponseData<Integer> deleteByPk(@RequestBody LmtFreezeAppVO inLmtFreezeAppVo) {
        int outputVo = lmtFreezeAppService.deleteByPk(inLmtFreezeAppVo);
        return getResponseData(outputVo);

    }

    /**
     * 根据主键更新信息
     *
     * @param inLmtFreezeAppVo
     * @return
     */
    @RequestMapping(value = "/lmt/freeze/app/{action}", method = RequestMethod.PUT)
    public @ResponseBody
    ResponseData<Integer> updateByPk(@RequestBody LmtFreezeAppVO inLmtFreezeAppVo, @PathVariable("action") String action) throws Exception {
        int outputVo = -1;
        inLmtFreezeAppVo.setAprvUserName("");
        inLmtFreezeAppVo.setAprvComment("");
        inLmtFreezeAppVo.setAprvDate("");
        outputVo = lmtFreezeAppService.updateByPk(inLmtFreezeAppVo);
        if (action.equals("save")) {
            return getResponseData(outputVo);
        } else if (action.equals("commit")) {
            LmtTerminateAppVO lmtTerminateAppVO = new LmtTerminateAppVO();
            lmtTerminateAppVO.setLmtContNo(inLmtFreezeAppVo.getLmtContNo());
            //是否存在“审批中”的额度终止申请
            List<LmtTerminateAppVO> lmtTerminateList = lmtTerminateAppService.querylmtTerminateByPk(lmtTerminateAppVO);
            if (lmtTerminateList.size() == 0) {
                return flowStart(inLmtFreezeAppVo);
            } else {
                return setResponseMessage(outputVo, "保存数据成功！流程发起失败：存在审批中的额度终止申请！ ");
            }
        }
        return getResponseData(outputVo);
    }

    /**
     * 新增数据
     *
     * @param inLmtFreezeAppVo
     * @return
     */
    @RequestMapping(value = "/lmt/freeze/app/{action}", method = RequestMethod.POST)
    public @ResponseBody
    ResponseData<Integer> insertLmtFreezeApp(@RequestBody LmtFreezeAppVO inLmtFreezeAppVo, @PathVariable("action") String action) throws Exception {
        int outputVo = -1;
        LmtTerminateAppVO lmtTerminateAppVO = new LmtTerminateAppVO();
        lmtTerminateAppVO.setLmtContNo(inLmtFreezeAppVo.getLmtContNo());
        //是否存在“审批中”的额度终止申请
        List<LmtTerminateAppVO> lmtTerminateList = lmtTerminateAppService.querylmtTerminateByPk(lmtTerminateAppVO);
        if (lmtTerminateList.size() == 0) {
            LmtFreezeAppVO lmtFreezeAppVO = new LmtFreezeAppVO();
            lmtFreezeAppVO = returnLmtFreezeAppInfo(inLmtFreezeAppVo);
            //inLmtFreezeApp 返回值不为null则说明不存在同一授信协议信息并未处理完成的数据
            if (lmtFreezeAppVO != null) {
                // 01:待发起，02:审批中 03:通过 04:拒绝 05:退回
                lmtFreezeAppVO.setApproveStatus(ConsoleConstant.APRV_STATUS_01);
                lmtFreezeAppVO.setAprvUserName("");
                lmtFreezeAppVO.setAprvComment("");
                lmtFreezeAppVO.setAprvDate("");
                outputVo = lmtFreezeAppService.insertLmtFreezeApp(lmtFreezeAppVO);

                if (action.equals("save")) {
                    return getResponseData(outputVo);
                } else if (action.equals("commit")) {
                    return flowStart(lmtFreezeAppVO);
                }
                return setResponseMessage(outputVo, "处理失败：非保存提交操作！ ");
            }
            return setResponseMessage(outputVo, "处理失败：该授信额度信息，存在未处理完成的额度冻结申请操作！ ");
        }
        return setResponseMessage(outputVo, "处理失败：该授信额度信息，存在未处理完成的额度终止申请！ ");

    }

    public LmtFreezeAppVO returnLmtFreezeAppInfo(LmtFreezeAppVO inLmtFreezeAppVo) throws Exception {
        LmtFreezeAppVO lmtFreezeApp = new LmtFreezeAppVO();
        //将lmtContNo为查询条件，查询同一授信协议信息并未处理完成的数据
        List<LmtFreezeAppVO> lmtContNoList = lmtFreezeAppService.queryLmtContNoByPk(inLmtFreezeAppVo);
        //如果不存在，则返回 0 将前端传入的数据赋给lmtFreezeApp
        if (lmtContNoList.size() == 0) {
            lmtFreezeApp.setCusId(inLmtFreezeAppVo.getCusId());
            lmtFreezeApp.setCusName(inLmtFreezeAppVo.getCusName());
            lmtFreezeApp.setCertType(inLmtFreezeAppVo.getCertType());
            lmtFreezeApp.setCertCode(inLmtFreezeAppVo.getCertCode());
            lmtFreezeApp.setLmtContNo(inLmtFreezeAppVo.getLmtContNo());
            lmtFreezeApp.setLmtAmt(inLmtFreezeAppVo.getLmtAmt());
            lmtFreezeApp.setAvailAmt(inLmtFreezeAppVo.getAvailAmt());
            lmtFreezeApp.setCyclicFlg(inLmtFreezeAppVo.getCyclicFlg());
            lmtFreezeApp.setStartDate(inLmtFreezeAppVo.getStartDate());
            lmtFreezeApp.setExpireDate(inLmtFreezeAppVo.getExpireDate());
            lmtFreezeApp.setChannelNo(inLmtFreezeAppVo.getChannelNo());
            lmtFreezeApp.setPrdId(inLmtFreezeAppVo.getPrdId());
            lmtFreezeApp.setPrdCode(inLmtFreezeAppVo.getPrdCode());
            lmtFreezeApp.setPrdName(inLmtFreezeAppVo.getPrdName());
            lmtFreezeApp.setCusManager(inLmtFreezeAppVo.getCusManager());

            lmtFreezeApp.setCreateUser(inLmtFreezeAppVo.getCreateUser());
            lmtFreezeApp.setCreateTime(TimeUtil.getCurrentDateTime());
            lmtFreezeApp.setLastUpdateUser(inLmtFreezeAppVo.getCreateUser());
            lmtFreezeApp.setLastUpdateTime(lmtFreezeApp.getCreateTime());
            lmtFreezeApp.setOrgCode(inLmtFreezeAppVo.getOrgCode());
            lmtFreezeApp.setApplyDate(pubSysInfoService.getOpenday(BaseConstant.SYS_ID_1001));//营业日期
            lmtFreezeApp.setFrzSerno(sequenceService.getSequence("FRZ_SERNO", "null", "null"));
            lmtFreezeApp.setFrzReason(inLmtFreezeAppVo.getFrzReason());
            return lmtFreezeApp;
        }
        //否则返回null
        return null;
    }

    private ResponseData<Integer> setResponseMessage(Integer outputVo, String message) {
        ResponseData<Integer> responseData = new ResponseData<Integer>();
        responseData.setMessage(message);
        responseData.setCode(ApplicationConstance.FAILURE);
        responseData.setSuccess(true);
        return responseData;
    }

    private ResponseData<Integer> flowStart(LmtFreezeAppVO lmtFreezeAppVO) {
        int outputVo = -1;
        setUserInfoToVO(lmtFreezeAppVO);
        if(lmtFreezeAppVO.getApproveStatus().equals(ConsoleConstant.APRV_STATUS_05)){
            flowRepulseUtil.cleanRepulseAllInfo(lmtFreezeAppVO.getFrzSerno());
        }
        logger.info("即将发起额度限额审批流程，信息为:" + JSON.toJSONString(lmtFreezeAppVO));
        // 事件ID
        String eventId = "mLmtFreezeAppEnter";
        // 获取流程ID
        String flowId = "FW20190923000000000";
        lmtFreezeAppVO.setApproveStatus(ConsoleConstant.APRV_STATUS_02);

        BizFlowInfoVO bizFlowInfoVO = new BizFlowInfoVO();
        bizFlowInfoVO.setBizFlowType(FlowConstance.BIZ_FLOW_TYPE_07);
        bizFlowInfoVO.setBizFlowId(flowId);
        List<BizFlowInfoVO> listFlow = bizFlowInfoService.queryBizFlowInfoByFlowType(bizFlowInfoVO);

        logger.info("查询到的业务流程参数为：" + JSONObject.toJSONString(listFlow));
        if (Objects.nonNull(listFlow) && listFlow.size() > 0) {
            bizFlowInfoVO = listFlow.get(0);
            flowId = bizFlowInfoVO.getBizFlowId();  // 得到业务流转ID
        } else {
            //提交失败 待发起
            outputVo = -1;
            return setResponseMessage(outputVo, "未配置相关信息提交失败!");
        }
        EngineHttpRequestVO eVo = new EngineHttpRequestVO();
        // 业务法人机构
        eVo.setBizLagelOrgCode(this.getUserInfo().getOrgInfo().getOrgCode());
        // 业务流水号
        eVo.setE_bizSerno(lmtFreezeAppVO.getFrzSerno());
        eVo.setFlowId(flowId);
        //事件ID
        eVo.setEventId(eventId);
        eVo.setData(lmtFreezeAppVO);
        eVo.setG_bizSerno(lmtFreezeAppVO.getFrzSerno());
        if (!flowCommonService.dutyFlowCheck(eventId,flowId)){
            outputVo = -1;
            return setResponseMessage(outputVo, "发起审批流程失败!原因: 流程岗位已失效");
        }
        try {
            HttpClientUtil.callFlowEngine(flowUrlConfigService.getRestfulSyncStartEventUrl(), eVo, String.class);
            outputVo = lmtFreezeAppService.updateByPk(lmtFreezeAppVO);
        } catch (Exception e) {
            // 发起失败
            e.printStackTrace();
            logger.error("LmtFreezeAppVO", e.getMessage());
            outputVo = -1;
            return setResponseMessage(outputVo, "发起额度限额审批流程失败!原因: " + e.getMessage());
        }
        return getResponseData(outputVo);
    }

    /**
     * 查询数据 贷款台账表
     *create by luzhaoyu
     * @param lmtFreezeAppVO
     * @return
     */
    @RequestMapping(value = "/lmt/freeze/loan", method = RequestMethod.POST)
    public @ResponseBody
    ResponseData<List<AccLoanVO>> queryAccLoanAll(
            @RequestBody LmtFreezeAppVO lmtFreezeAppVO) {
        List<AccLoanVO> outputVo = null;
        AccLoanVO accLoanVO = new AccLoanVO();
        String certType = lmtFreezeAppVO.getCertType();
        String certCode = lmtFreezeAppVO.getCertCode();
        accLoanVO.setCertCode(certCode);
        accLoanVO.setCertType(certType);
        accLoanVO.setPage(lmtFreezeAppVO.getPage());
        accLoanVO.setSize(lmtFreezeAppVO.getSize());
        accLoanVO.setTotal(lmtFreezeAppVO.getTotal());
        outputVo = accLoanService.queryAccLoan(accLoanVO);
        return getResponseData(outputVo);
    }
}
